import java.net.ServerSocket;
import java.net.Socket;

import data.DBLoader;
import data.Database;

/*
 * TODO:
 * Create a time-out system to prevent an idling thread from taking up resources.  Is it necessary to loop?  Probably.
 */

public class Server {
	static ServerSocket servSock = null;
	private static RequestThread r;

	public static void main(String[] args) {
		final int PORT = 8576;

		
		//set up serversocket to listen for connections
		try {
			servSock = new ServerSocket(PORT);
		} catch (Exception e) {
			System.out.println("Could not start serversocket.  Exiting.");
			System.exit(1);
		}
		System.out.println("Server initialized.  Waiting for connection on port " + PORT);
		
		//setup database
		Database db = DBLoader.getDB("db.db");
		System.out.println("DB Size: " + db.getSize());

		//use to build test database
//		Database db = new Database();
//		db.testSetup();
//		DBLoader.saveDB(db, "db.db");
		
		
		while ( servSock != null ) {
			Socket tempSock;
			try {
				tempSock = servSock.accept();
				System.out.println("Recieved new Connection.");
				r = new RequestThread( tempSock , db );
				r.start();
			} catch (Exception e) {
				System.out.println( "Failure connecting to new client.  Exiting. ");
				System.exit(1);
			}
			
			try { Thread.sleep(100); } catch (Exception e) {};
		}
	}

	public void finalize() {
		try {
			r.close();
			servSock.close();
		} catch (Exception e) {};
		servSock = null;
	}
}
